package xing.application.service.isv.suite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xing.application.api.CorpApi;
import xing.application.service.BaseService;
import xing.domain.isv.suite.CorpSuiteAuth;
import xing.domain.isv.suite.CorpToken;
import xing.domain.isv.suite.LoginUser;
import xing.infrastructure.util.StringUtil;
import xing.repository.isv.suite.CorpSuiteAuthRepository;

import java.util.List;

/*******************************************************************************************
 * 类描述：  
 *
 * @author: dustin
 * @date： 2017-8-31 15:04
 * @Description:
 * @version 1.0.0
 *
 *
 * Version    Date       ModifiedBy                 Content  
 * -------- ---------    ----------         ------------------------  
 * 1.0.0     2017-8-31    Administrator                            
 *******************************************************************************************
 */
@Service
public class CorpAuthService extends BaseService {

    @Autowired
    private CorpSuiteAuthRepository corpSuiteAuthRepository;

    @Autowired
    private CorpTokenService corpTokenService;

    @Autowired
    private CorpApi corpApi;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public LoginUser getUserByAuthCode(String corpId,String code) throws Exception{
        long timeStamp = System.currentTimeMillis() / 1000;
        String nonceStr = StringUtil.getString(6);
        List<CorpSuiteAuth> corpSuiteAuths = corpSuiteAuthRepository.findAllByCorpId(corpId);
        if(null!=corpSuiteAuths && corpSuiteAuths.size()>0) {
            logger.info("获取corpSuiteAuths Count:"+corpSuiteAuths.size());
            String suiteKey=corpSuiteAuths.get(0).getSuiteKey();
            CorpToken ck= corpTokenService.getCorpToken(suiteKey,corpId);
            String accessToken= ck.getCorpToken();
            LoginUser u = corpApi.getCurrentUserByAuthCode(suiteKey,corpId,accessToken,code);
            logger.info("获取当前用户",u);
            return u;
        }else{
            logger.error("获取当前用户失败，找不到对应套件！");
        }
        return null;
    }


}
